import {useMenuListStore} from "@/stores/counter";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from "@/router/index";
import type {RouteRecordName} from "vue-router";
import {constructMenuRouter} from "@/router/ConstructMenuRouter";
import {ElNotification} from "element-plus";
import {hasToken} from "@/util/TokenUtil";
import type {MenuTypes} from "@/resources/interface/sys/MenuTypes";

NProgress.configure({
    easing: 'ease', // 动画方式
    speed: 1000, // 递增进度条的速度
    showSpinner: false, // 是否显示加载ico
    trickleSpeed: 200, // 自动递增间隔
    minimum: 0.3 // 初始化时的最小百分比
})

export const routes: MenuTypes[] = [{
    router: '/',
    name: '工作台',
    component: '/base/MainView',
    icon: '',
    type: 0,
    children: [
        {router: '', name: '首页', icon: 'Menu', type: 0, component: '/base/IndexView'}
    ]
}]
const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
    NProgress.start()
    if (hasToken()) {
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            let menuListStore = useMenuListStore();
            // 路由不存在
            if (menuListStore.menuList && menuListStore.menuList.length === 0) {
                //pinia没有数据
                // 获取菜单
                await constructMenuRouter([]);
                next({...to, replace: true})
            } else {
                // pinia有数据
                //写入路由
                await constructMenuRouter(menuListStore.menuList);
                router.hasRoute(to.name as RouteRecordName) ? next() : next({path: to.path, replace: true})
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            ElNotification.error("请重新登录")
            next({path: '/login'})
        }

    }

})

router.afterEach(() => {
    NProgress.done();
})
